package com.jindu.producer.finance.controller;


import com.jindu.kernel.result.JsonResult;
import com.jindu.kernel.utils.AlphaBeanUtils;
import com.jindu.kernel.utils.DateUtils;
import com.jindu.kernel.utils.IdGenerator;
import com.jindu.producer.finance.jpa.FiscalResultJpa;
import com.jindu.producer.finance.jpa.FiscalTaxJpa;
import com.jindu.producer.finance.jpa.HightechJpa;
import com.jindu.producer.finance.jpa.LegalJpa;
import com.jindu.producer.finance.model.FFiscalResultEntity;
import com.jindu.producer.finance.model.FFiscalTaxEntity;
import com.jindu.producer.finance.model.FHightechEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;

/**
 * @author jarvis
 * @date 2018/10/18
 */
@Api(description = "财税评测项", tags = "FiscalTaxController", basePath = "/fiscalTax")
@RestController
@RequestMapping(value = "/fiscalTax",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class FiscalTaxController {

    Logger logger = LoggerFactory.getLogger(FiscalTaxController.class);

    @Autowired
    FiscalTaxJpa fiscalTaxJpa;

    @Autowired
    FiscalResultJpa fiscalResultJpa;

    @Autowired
    HightechJpa hightechJpa;

    @Autowired
    LegalJpa legalJpa;


    @ApiOperation(value = "根据财税评测项的ID，查询财税评测项的信息", notes = "返回单个财税评测项的信息")
    @RequestMapping(value = "get",method = RequestMethod.GET)
    public JsonResult<FFiscalTaxEntity> get(@RequestParam String id){
        return JsonResult.getSuccessResult(fiscalTaxJpa.findById(id));
    }


    @ApiOperation(value = "根据录入的数据，查询财税评测项的结构信息", notes = "返回财税评测项的结果集合")
    @RequestMapping(value = "getResult",method = RequestMethod.GET)
    public JsonResult<List<FFiscalTaxEntity>> getResult(@RequestParam(value = "orgId", required = true) Integer orgId){

        List<FFiscalTaxEntity> entities=getTaxResult(orgId);
        return JsonResult.getSuccessResult(entities);
    }


    /**
     * 根据 orgId 查询信息，把通用方法抽取出来
     * @param orgId
     * @return
     */
    private List<FFiscalTaxEntity> getTaxResult(Integer orgId){

        Sort sort = new Sort(Sort.Direction.ASC, "itemId");
        List<FFiscalTaxEntity> entities=fiscalTaxJpa.findAll(sort);

        List<FFiscalResultEntity> param=fiscalResultJpa.findByOrgId(orgId);
        HashMap<Integer,BigDecimal> begin=new HashMap<>();
        HashMap<Integer,BigDecimal> end=new HashMap<>();

        for(int i=1;i<21;i++){
            FFiscalResultEntity fr=new FFiscalResultEntity();
            for (FFiscalResultEntity fre :param){
                if (fre.getItemId()==i){
                    fr=fre;
                }
            }
            begin.put(i,fr.getValue()!=null?fr.getValue():BigDecimal.valueOf(0));
            end.put(i,fr.getValue2()!=null?fr.getValue2():BigDecimal.valueOf(0));
        }
        BigDecimal[] value=new BigDecimal[17];
        for (int n=0;n<value.length;n++){
            value[n]=BigDecimal.valueOf(0);
        }

        //流动比率:流动资产/流动负债
        if(end.get(9).compareTo(BigDecimal.valueOf(0))!=0){
            value[1]= end.get(3).divide(end.get(9),2);
        }
        //速动比率:(流动资产-存货）/流动负债
        if(end.get(9).compareTo(BigDecimal.valueOf(0))!=0){
            value[2]= (end.get(3).subtract(end.get(6))).divide(end.get(9),2);
        }
        //资产负债率:负债总额/资产总额
        if(end.get(1).compareTo(BigDecimal.valueOf(0))!=0){
            value[3]= end.get(8).divide(end.get(1),2);
        }
        //产权比例:负债总额/所有者权益（净资产）
        if(end.get(2).compareTo(BigDecimal.valueOf(0))!=0){
            value[4]=end.get(8).divide(end.get(2),2);
        }
        //有形净值债务率:总负债/（净资产-无形-递延资产）
        if((end.get(2).subtract(end.get(4)).subtract(end.get(5))).compareTo(BigDecimal.valueOf(0))!=0){
            value[5]=end.get(8).divide(end.get(2).subtract(end.get(4)).subtract(end.get(5)),2);
        }
        //利息保障倍数:（利润总额+财务费用）/ 财务费用
        if(end.get(15).compareTo(BigDecimal.valueOf(0))!=0){
            value[6]= (end.get(13).add(end.get(15))).divide(end.get(15),2);
        }

        //销售利润率:营业利润/销售收入
        if(end.get(12).compareTo(BigDecimal.valueOf(0))!=0){
            value[7]=end.get(13).divide(end.get(12),2);
        }
        //销售净利率:净利润 / 销售（营业）收入
        if(end.get(12).compareTo(BigDecimal.valueOf(0))!=0){
            value[8]= end.get(14).divide(end.get(12),2);
        }
        //总资产净利率:净利润/平均总资产
        if((begin.get(1).add(end.get(1))).compareTo(BigDecimal.valueOf(0))!=0){
            value[9]=end.get(14).divide((begin.get(1).add(end.get(1))).divide(BigDecimal.valueOf(2),2),2);
        }
        //总资产报酬率:(利润总额+利息总额)/平均总资产
        if((begin.get(1).add(end.get(1))).compareTo(BigDecimal.valueOf(0))!=0){
            value[10]=(end.get(13).add(end.get(16))).divide((begin.get(1).add(end.get(1))).divide(BigDecimal.valueOf(2),2),2);
        }

        //应收账款周转天数:计算期天数/销售收入*应收账款平均余额
        if(end.get(12).multiply((begin.get(10).add(end.get(10)))).compareTo(BigDecimal.valueOf(0))!=0){
            value[11]=BigDecimal.valueOf(365).divide(end.get(12).multiply((begin.get(10).add(end.get(10))).divide(BigDecimal.valueOf(2),2)),2);
        }
        //应付账款周转天数:计算期天数/销售成本*应付账款平均余额
        if(end.get(19).multiply((begin.get(11).add(end.get(11))).divide(BigDecimal.valueOf(2),2)).compareTo(BigDecimal.valueOf(0))!=0){
            value[12]=BigDecimal.valueOf(365).divide(end.get(19).multiply((begin.get(11).add(end.get(11))).divide(BigDecimal.valueOf(2),2)),2);
        }
        //存货周转天数:计算期天数/销售成本*平均存货
        if(end.get(19).multiply((begin.get(6).add(end.get(6)))).compareTo(BigDecimal.valueOf(0))!=0){
            value[13]=BigDecimal.valueOf(365).divide(end.get(19).multiply((begin.get(6).add(end.get(6)).divide(BigDecimal.valueOf(2),2))),2);
        }
        //营业周期 : 存货周转天数+应收账款周转天数
        value[14]= value[13].add(value[11]);

        //销售收现比率:销售收现比率=销售商品提供劳务收到的现金÷主营业务收入净额
        if(end.get(12).compareTo(BigDecimal.valueOf(0))!=0){
            value[15]=end.get(18).divide(end.get(12),2) ;
        }
        //资产现金回收率:资产现金回收率=经营现金净流量/平均总资产
        if(begin.get(1).add(end.get(1)).compareTo(BigDecimal.valueOf(0))!=0){
            value[16]=end.get(17).divide((begin.get(1).add(end.get(1))).divide(BigDecimal.valueOf(2),2),2);
        }

        logger.warn("1流动比率:"+value[1]);
        logger.warn("2速动比率:"+value[2]);
        logger.warn("3资产负债率:"+value[3]);
        logger.warn("4产权比例:"+value[4]);
        logger.warn("5有形净值债务率:"+value[5]);
        logger.warn("6利息保障倍数:"+value[6]);

        logger.warn("7销售利润率:"+value[7]);
        logger.warn("8:销售净利率"+value[8]);
        logger.warn("9:总资产净利率"+value[9]);
        logger.warn("10:总资产报酬率"+value[10]);

        logger.warn("11应收账款周转天数:"+value[11]);
        logger.warn("12:应付账款周转天数"+value[12]);
        logger.warn("13:存货周转天数"+value[13]);
        logger.warn("14:营业周期"+value[14]);

        logger.warn("15:销售收现比率"+value[15]);
        logger.warn("16:资产现金回收率"+value[16]);

        for (int j=0;j<entities.size();j++){
            entities.get(j).setOrgId(orgId);
            entities.get(j).setValue(value[j+1]);
        }

        return  entities;

    }


    @ApiOperation(value = "保存和修改 财税评测项的信息", notes = "保存财税评测项 的信息")
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public JsonResult<FFiscalTaxEntity> save(@RequestBody FFiscalTaxEntity fiscalTaxEntity){

        FFiscalTaxEntity fFiscalTaxEntity=fiscalTaxJpa.findById(fiscalTaxEntity.getId());

        if(fFiscalTaxEntity == null){
            fiscalTaxEntity.setId(IdGenerator.uuid());
            fiscalTaxEntity.setCreateTime(new Timestamp(DateUtils.getCurrentTime()));
            fiscalTaxEntity.setModifyTime(new Timestamp(DateUtils.getCurrentTime()));
            return JsonResult.getSuccessResult(fiscalTaxJpa.saveAndFlush(fiscalTaxEntity));
        }else {
            fiscalTaxEntity.setModifyTime(new Timestamp(DateUtils.getCurrentTime()));
            BeanUtils.copyProperties(fiscalTaxEntity,fFiscalTaxEntity, AlphaBeanUtils.getNullPropertyNames(fiscalTaxEntity));
            return JsonResult.getSuccessResult(fiscalTaxJpa.saveAndFlush(fFiscalTaxEntity));
        }
    }


    @ApiOperation(value = "根据OrgId，或者完整的报告的数据信息", notes = "获取完整的该报告的信息")
    @RequestMapping(value = "getReport", method = RequestMethod.GET)
    public JsonResult<HashMap<String,Object>> getReport(@RequestParam(value = "orgId", required = true) Integer orgId){

        HashMap<String,Object> result=new HashMap<>();
        if(orgId!=null){


            FHightechEntity hightechEntity=hightechJpa.findByOrgId(orgId);
            result.put("hightech",hightechEntity);

            List<FFiscalTaxEntity> entities=getTaxResult(orgId);
            result.put("taxResult",entities);

            return JsonResult.getSuccessResult(result);

        }else {

            return JsonResult.getSuccessResult(result);
        }

    }




}
